package mulMan.domain;

import java.io.File;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

import mulMan.services.AudioFileServices;

public class AudioFileModel extends Observable implements Observer{
	
	private AudioFile audioFile;
	private AudioFileServices audioFileServices;
	
	
	
	public AudioFileServices getAudioFileServices() {
		return audioFileServices;
	}
	public void setAudioFileServices(AudioFileServices audioFileServices) {
		this.audioFileServices = audioFileServices;
	}
	
	public String getTitle() {
		return audioFile.getTitle();
	}
	public void setTitle(String title) {
		audioFile.setTitle(title);
	}
	public String getArtist() {
		return audioFile.getArtist();
	}
	public void setArtist(String artist) {
		audioFile.setArtist(artist);
	}
	public String getAlbum() {
		return audioFile.getAlbum();
	}
	public void setAlbum(String album) {
		audioFile.setAlbum(album);
	}
	public String getPath() {
		return audioFile.getPath();
	}
	public void setPath(String path) {
		audioFile.setPath(path);
	}
	public Integer getLength() {
		return audioFile.getLength();
	}
	public void setLength(Integer length) {
		audioFile.setLength(length);
	}
	
	


	public AudioFileModel() {
		audioFile = new AudioFile();
		audioFile.addObserver(this);

	}
	

	public AudioFile getAudioFile() {
		return audioFile;
	}
	public void setAudioFile(AudioFile audioFile) {
		this.audioFile = audioFile;
		audioFile.addObserver(this);
		setChanged();
		notifyObservers("all");
	}
	
	public void saveAudioFile() throws Exception {
		audioFileServices.saveAudioFile(audioFile);
	}
	
	public void updateAudioFile() throws Exception {
		audioFileServices.updateAudioFile(audioFile);
	}
	
	public void deleteAudioFile() throws Exception {
		audioFileServices.deleteAudioFile(audioFile);
		audioFile.setIdAudioFile(0);
		setChanged();
	}


	public void update(Observable arg0, Object arg1) {
		setChanged();
		notifyObservers(arg1);
	}
	
	public String toString() {
		return audioFile.toString();
	}
	
	public void play() throws UnsupportedAudioFileException, IOException, LineUnavailableException {
		File soundFile = new File(audioFile.getPath());
	    AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);
	    
	    DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
	    Clip clip = (Clip) AudioSystem.getLine(info);
	    clip.open(sound);
	    
	    clip.start();
	}
}
